/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software Foundation,
 *    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

/*
 * MaterialsDialog.java
 *
 * Created on 2009-12-13, 19:07:06
 */

package JET.Frames.materialsframe;

import JET.StaticActions;
import JET.Centers.ControlCenter;
import JET.SA.SA_Dialogs;
import JET.Scene;
import JET.physics.MaterialPair;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

/**
 *
 * @author 057Ry
 */
public class MaterialsDialog extends javax.swing.JDialog
{
    static final ControlCenter CC = ControlCenter.getInstance();
    private int material1Index;
    private int material2Index;
    private MaterialsTableMouseInputListener mil;

    private Scene scene;

    /** Creates new form MaterialsDialog */
    public MaterialsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        jTable1.setFillsViewportHeight(true);
        jTable1.setCellSelectionEnabled(true);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.getTableHeader().setResizingAllowed(false);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.setDefaultRenderer(MaterialPair.class, new MaterialsCellRenderer());
        
        resetCellsWidthTo(50);
        initRowHeader(null);

        //jTable1.getSelectionModel().addListSelectionListener(new MaterialsTableSelectionListener(CC,jTable1, this));
        mil = new MaterialsTableMouseInputListener(this);
        jTable1.addMouseListener(mil);
        jTable1.addMouseMotionListener(mil);
    }

    public void setScene(Scene s) {
        scene = s;
        //((MaterialsTableModel)jTable1.getModel()).setScene(scene);
        //((RowHeaderTableModel)((JTable)jScrollPane1.getRowHeader().getView()).getModel()).setScene(scene);
        //initRowHeader(scene);
        mil.setScene(scene);
        updateTable();
    }
    private void resetCellsWidthTo(int width)
    {
        for(int i=0; i<jTable1.getColumnModel().getColumnCount(); i++)
        {
            TableColumn tc = jTable1.getColumnModel().getColumn(i);
            tc.setPreferredWidth(width);
        }
    }
    private void initRowHeader(Scene s)
    {
        RowHeaderTableModel rhtm = new RowHeaderTableModel();
        rhtm.setScene(s);
        JTable rowHeader = new JTable(rhtm);
        rowHeader.setIntercellSpacing(new Dimension(0, 0));
        Dimension d = rowHeader.getPreferredScrollableViewportSize();
        d.width = rowHeader.getPreferredSize().width;
        rowHeader.setPreferredScrollableViewportSize(d);
        rowHeader.setRowHeight(jTable1.getRowHeight());
        rowHeader.setDefaultRenderer(Object.class, new RowHeaderRenderer());

        JScrollPane scrollPane = jScrollPane1;

        scrollPane.setRowHeaderView(rowHeader);

        JTableHeader corner = rowHeader.getTableHeader();
        corner.setReorderingAllowed(false);
        corner.setResizingAllowed(false);

        scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, corner);
    }

    public void setSelectedCell(int row, int col)
    {
        jTable1.scrollRectToVisible(jTable1.getCellRect(row, col, true));
        jTable1.changeSelection(row, col, false, false);
    }

    public void setMaterial1Name(String name)
    {
        material1TextField.setText(name);
    }
    public void setMaterial2Name(String name)
    {
        material2TextField.setText(name);
    }
    public void setMaterial1Index(int i)
    {
        material1Index = i;
    }
    public void setMaterial2Index(int i)
    {
        material2Index = i;
    }
    public void setBounceValue(double value)
    {
        bounceTextField.setText(""+value);
    }
    public void setFrictionValue(double value)
    {
        frictionTextField.setText(""+value);
    }
    public void setCollisionCheckBoxSelected(boolean selected)
    {
        collisionCheckBox.setSelected(selected);
    }

    public double getBounceGUIValue()
    {
        return Double.parseDouble(bounceTextField.getText());
    }

    public double getFrictionGUIValue()
    {
        return Double.parseDouble(frictionTextField.getText());
    }

    public void setBounceByGUIValue()
    {
        try
        {
            double value = getBounceGUIValue();
            MaterialPair matP = scene.getJETContext().materials[material1Index][material2Index];
            matP.elasticity = value;
            matP = scene.getJETContext().materials[material2Index][material1Index];
            matP.elasticity = value;
            jTable1.updateUI();
        }
        catch(NumberFormatException ex){
            System.out.println("Nie moge zamenic takiego ("+bounceTextField.getText()+") stringa na liczbe double.");
            return;
        }
    }
    public void setFrictionByGUIValue()
    {
        try
        {
            double value = getFrictionGUIValue();
            MaterialPair matP = scene.getJETContext().materials[material1Index][material2Index];
            matP.friction = value;
            matP = scene.getJETContext().materials[material2Index][material1Index];
            matP.friction = value;
            jTable1.updateUI();
        }
        catch(NumberFormatException ex){
            System.out.println("Nie moge zamenic takiego ("+frictionTextField.getText()+") stringa na liczbe double.");
            return;
        }
    }
    public void setCollisionByGUIValue()
    {
        MaterialPair matP = scene.getJETContext().materials[material1Index][material2Index];
        matP.collide = collisionCheckBox.isSelected();
        matP = scene.getJETContext().materials[material2Index][material1Index];
        matP.collide = collisionCheckBox.isSelected();
        jTable1.updateUI();
    }

    public void setBounceGUIValue(double value)
    {
        bounceTextField.setText(""+value);
    }
    public void setFrictionGUIValue(double value)
    {
        frictionTextField.setText(""+value);
    }
    public void setCollisionGUIValue(boolean value)
    {
        collisionCheckBox.setSelected(value);
    }

    public void updateTable()
    {
        MaterialsTableModel mtm = new MaterialsTableModel();
        mtm.setScene(scene);
        jTable1.setModel(mtm);
        resetCellsWidthTo(50);
        initRowHeader(scene);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        material1TextField = new javax.swing.JTextField();
        material2TextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        collisionCheckBox = new javax.swing.JCheckBox();
        bounceTextField = new javax.swing.JTextField();
        frictionTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        newMaterialButton = new javax.swing.JButton();
        removeMaterialButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Materials");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Material Pair"));

        jLabel1.setText("Material 1 name :");

        jLabel2.setText("Material 2 name :");

        material1TextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                material1TextFieldKeyPressed(evt);
            }
        });

        material2TextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                material2TextFieldKeyPressed(evt);
            }
        });

        jLabel3.setText("Elasticity :");

        jLabel4.setText("Friction :");

        collisionCheckBox.setText("collide");
        collisionCheckBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                collisionCheckBoxItemStateChanged(evt);
            }
        });

        bounceTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bounceTextFieldKeyPressed(evt);
            }
        });

        frictionTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                frictionTextFieldKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(collisionCheckBox)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2))
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(material2TextField, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                            .addComponent(material1TextField, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                            .addComponent(bounceTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                            .addComponent(frictionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(material1TextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(material2TextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addComponent(jLabel1))
                .addGap(44, 44, 44)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(bounceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(frictionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(collisionCheckBox)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTable1.setModel(new MaterialsTableModel());
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setRowHeight(50);
        jTable1.setRowSelectionAllowed(false);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);

        newMaterialButton.setText("New Material");
        newMaterialButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newMaterialButtonActionPerformed(evt);
            }
        });

        removeMaterialButton.setText("Remove Materials");
        removeMaterialButton.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(newMaterialButton, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeMaterialButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(newMaterialButton)
                            .addComponent(removeMaterialButton)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void material1TextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_material1TextFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            scene.getJETContext().materialNames[material1Index] = material1TextField.getText();
            //update table header
            TableColumn column = jTable1.getColumnModel().getColumn(material1Index);
            column.setHeaderValue(""+material1TextField.getText());
            jTable1.getTableHeader().repaint();
            // updtae rest of table (row header)
            jTable1.updateUI();
        }
    }//GEN-LAST:event_material1TextFieldKeyPressed

    private void material2TextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_material2TextFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            scene.getJETContext().materialNames[material2Index] = material2TextField.getText();
            //update table header
            TableColumn column = jTable1.getColumnModel().getColumn(material2Index);
            column.setHeaderValue(""+material2TextField.getText());
            jTable1.getTableHeader().repaint();
            // updtae rest of table (row header)
            jTable1.updateUI();
        }
    }//GEN-LAST:event_material2TextFieldKeyPressed

    private void newMaterialButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newMaterialButtonActionPerformed
        StaticActions.addNewMaterial(scene);
}//GEN-LAST:event_newMaterialButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        SA_Dialogs.setVisibleMaterialsDialog(false);
    }//GEN-LAST:event_formWindowClosed

    private void bounceTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bounceTextFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            setBounceByGUIValue();
            setBounceGUIValue(scene.getJETContext().materials[material1Index][material2Index].elasticity);
        }
    }//GEN-LAST:event_bounceTextFieldKeyPressed

    private void frictionTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_frictionTextFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            setFrictionByGUIValue();
            setFrictionGUIValue(scene.getJETContext().materials[material1Index][material2Index].friction);
        }
    }//GEN-LAST:event_frictionTextFieldKeyPressed

    private void collisionCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_collisionCheckBoxItemStateChanged
        setCollisionByGUIValue();
    }//GEN-LAST:event_collisionCheckBoxItemStateChanged



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField bounceTextField;
    private javax.swing.JCheckBox collisionCheckBox;
    private javax.swing.JTextField frictionTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField material1TextField;
    private javax.swing.JTextField material2TextField;
    private javax.swing.JButton newMaterialButton;
    private javax.swing.JButton removeMaterialButton;
    // End of variables declaration//GEN-END:variables

}
